import axios from "axios"
import {ElMessage} from "element-plus";
import {getToken} from "@/api/cookie.js";

const axiosService = axios.create({
    baseURL: '/dev-api',
    timeout: 10000,
    headers: {
        'Content-Type': 'application/json;charset=utf-8'
    }
})

// 前端请求拦截器
axiosService.interceptors.request.use(
    (config) => {
        if (getToken()) {
            // 如果有token，代表放入了token，需要携带token一起发送给后端
            config.headers["Authorization"] = getToken()
        }
        return config;
    },
    (error) => {
        console.log(error)
        Promise.reject(error)
    }
)

// 前端响应拦截器
axiosService.interceptors.response.use(
    (result) => {
        const code = result.data.code
        const message = result.data.message
        if (code !== '0') {
            ElMessage.error(message)
            return Promise.reject(new Error(message))
        } else {
            return Promise.resolve(result.data)
        }
    },
    (error) => {
        ElMessage.error(error.data.message)
        return Promise.reject(error)
    }
)

export default axiosService